package com.desktopmng.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;

import com.desktopmng.core.support.Pager;
import com.desktopmng.exception.JFossException;
import com.desktopmng.orm.Role;

@SuppressWarnings({"unchecked","rawtypes"})
public class RoleManager extends HibernateEntityDao<Role> {

	
	public List findRoleByType(Character roleType) throws DataAccessException {
		List<Role> roleList = new ArrayList<Role>();
		String sql = "SELECT R.* FROM T_JFOSS2_ROLE R WHERE R.ROLE_TYPE='"
				+ roleType + "' ";
		Session s = getSession();
		Query query = s.createSQLQuery(sql).addEntity(Role.class);
		roleList = query.list();
		return roleList;
	}

	/**
	 * 增加角色
	 * 
	 * @param role
	 * @param hgroup
	 * @param huser
	 * @return
	 * @throws JFossException
	 */
	public boolean addRole(Role role, HashSet<Long> hgroup, HashSet<Long> huser)
			throws JFossException {
		boolean isSave = false;
		try {
			// rolePeer.setCreateTime(new Date());
			role.setRoleType('0');
			// RolePeer role=roleDao.saveOrUpdateRole(rolePeer);
			isSave = this.save(role);
			if (role != null && isSave == true) {
				// if(huser!=null&&huser.size()>0){
				this.addUserToRole(role, huser);
				// }
				// if(hgroup!=null&&hgroup.size()>0){
				this.addGroupToRole(role, hgroup);
				// }
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new JFossException(e);
		}
		return isSave;
	}

	public void addUserToRole(Role role, HashSet<Long> huser) {
		Long roleId = role.getId();
		Set<Long> users = huser;
		if (roleId != null) {
			String sql = "";
			Session s = getSession();
			String sql1 = "DELETE FROM T_JFOSS2_USER_TO_ROLE WHERE ROLE_ID="
					+ roleId;
			s.createSQLQuery(sql1).executeUpdate();
			if (users != null && users.size() > 0) {
				for (Iterator it = users.iterator(); it.hasNext();) {
					Long userId = (Long) it.next();
					sql = "INSERT INTO T_JFOSS2_USER_TO_ROLE(USER_ID,ROLE_ID) VALUES("
							+ userId + "," + roleId + ")";
					s.createSQLQuery(sql).executeUpdate();
				}
			}
		}
	}

	public void addGroupToRole(Role role, HashSet<Long> hgroup) {
		Long roleId = role.getId();
		Set<Long> groups = hgroup;
		if (roleId != null) {
			String sql = "";
			Session s = getSession();
			String sql1 = "DELETE FROM T_JFOSS2_ROLE_TO_GROUP WHERE ROLE_ID="
					+ roleId;
			s.createSQLQuery(sql1).executeUpdate();
			if (groups != null && groups.size() > 0) {
				for (Iterator it = groups.iterator(); it.hasNext();) {
					Long groupId = (Long) it.next();
					sql = "INSERT INTO T_JFOSS2_ROLE_TO_GROUP(GROUP_ID,ROLE_ID) VALUES("
							+ groupId + "," + roleId + ")";
					s.createSQLQuery(sql).executeUpdate();
				}
			}
		}
	}

	/**
	 * 修改角色
	 * 
	 * @param rolePeer
	 * @return
	 * @throws JFossException
	 */
	public void updateRole(Role role, HashSet<Long> hgroup, HashSet<Long> huser)
			throws JFossException {
		try {
			this.merge(role);
			// RolePeer role=roleDao.mergeRole(rolePeer);
			if (role != null) {
				if (huser != null && huser.size() > 0) {
					this.addUserToRole(role, huser);
				}
				if (hgroup != null && hgroup.size() > 0) {
					this.addGroupToRole(role, hgroup);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new JFossException(e);
		}
	}

	/**
	 * 增加组和角色表
	 * 
	 * @param groupList
	 * @param roleId
	 * @throws JFossException
	 */
	public void addGroupToRole(List<Long> groupList, Long roleId)
			throws JFossException {
		try {
			if (roleId != null) {
				String sql = "";
				Session s = getSession();
				String sql1 = "DELETE FROM T_JFOSS2_ROLE_TO_GROUP WHERE ROLE_ID="
						+ roleId;
				s.createSQLQuery(sql1).executeUpdate();
				if (groupList != null && groupList.size() > 0) {
					for (int i = 0; i < groupList.size(); i++) {
						Long groupId = (Long) groupList.get(i);
						sql = "INSERT INTO T_JFOSS2_ROLE_TO_GROUP(GROUP_ID,ROLE_ID) VALUES("
								+ groupId + "," + roleId + ")";
						s.createSQLQuery(sql).executeUpdate();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new JFossException(e);
		}

	}

	/**
	 * 增加用户角色表
	 * 
	 * @param userList
	 * @param roleId
	 * @throws JFossException
	 */
	public void addUserToRole(List<Long> userList, Long roleId)
			throws JFossException {
		try {
			if (roleId != null) {
				String sql = "";
				Session s = getSession();
				String sql1 = "DELETE FROM T_JFOSS2_USER_TO_ROLE WHERE ROLE_ID="
						+ roleId;
				s.createSQLQuery(sql1).executeUpdate();
				if (userList != null && userList.size() > 0) {
					for (int i = 0; i < userList.size(); i++) {
						Long userId = (Long) userList.get(i);
						sql = "INSERT INTO T_JFOSS2_USER_TO_ROLE(USER_ID,ROLE_ID) VALUES("
								+ userId + "," + roleId + ")";
						s.createSQLQuery(sql).executeUpdate();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new JFossException(e);
		}
	}

	
	public List<Long> findResourceIdByRoleId(Long roleId) throws JFossException {

		Session s = getSession();
		try {
			String sql = "SELECT RESOURCE_ID FROM T_JFOSS2_RESOURCE_TO_ROLE WHERE ROLE_ID="
					+ roleId;
			List<Long> resourceIds = s.createSQLQuery(sql).addScalar(
					"RESOURCE_ID", Hibernate.LONG).list(); // 设置查询结果转换类型
			List<Long> resourceIdList = new ArrayList<Long>();
			if (resourceIds != null && resourceIds.size() > 0) {
				for (int i = 0; i < resourceIds.size(); i++) {
					resourceIdList.add(resourceIds.get(i));
				}
			}
			return resourceIdList;
		} catch (Exception e) {
			e.printStackTrace();
			throw new JFossException(e);
		}
	}


	public Pager findRoleByCondition(int pageNo, int pageSize, Properties prop) {
		String hql = "from Role r where r.roleType != '2' ";
		String sort = prop.getProperty("sort");
		if (StringUtils.isNotEmpty(sort)) {
			hql += "order by r." + sort.split("_")[0] + " "
					+ sort.split("_")[1];
		}
		return this.pagedQuery(hql, pageNo, pageSize);

	}
	
	public Role findRoleById(Long roleId) {
		return get(roleId);
	}

	public void addResourceToRole(List<Long> resourceList, Long roleId)
			throws JFossException {
		Session s = getSession();
		try {
			if (roleId != null) {
				String sql = "";
				String sql1 = "DELETE FROM T_JFOSS2_RESOURCE_TO_ROLE WHERE ROLE_ID="
						+ roleId;
				s.createSQLQuery(sql1).executeUpdate();
				if (resourceList != null && resourceList.size() > 0) {
					for (int i = 0; i < resourceList.size(); i++) {
						Long resourceId = (Long) resourceList.get(i);
						sql = "INSERT INTO T_JFOSS2_RESOURCE_TO_ROLE(RESOURCE_ID,ROLE_ID) VALUES("
								+ resourceId + "," + roleId + ")";
						s.createSQLQuery(sql).executeUpdate();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new JFossException(e);
		}
	}

	public List<Role> findRolesByUserId(Long userId) throws JFossException {
		List rolesList = null;
		Session s = getSession();
		if (userId != null) {
			String sql1 = "select r.* from T_JFOSS2_ROLE R, T_JFOSS2_USER_TO_ROLE UR where UR.user_Id="
					+ userId + " and R.ROLE_ID=UR.ROLE_ID";
			rolesList = s.createSQLQuery(sql1).addEntity(Role.class).list();

		}

		return rolesList;
	}

	public String deleteRole(Long id) {
		Session s = getSession();
		String sql1 = "SELECT USER_ID FROM T_JFOSS2_USER_TO_ROLE WHERE ROLE_ID="
				+ id;
		List userList = s.createSQLQuery(sql1).list();
		if (userList != null && userList.size() > 0) {
			return "1";
		}
		String sql2 = "SELECT GROUP_ID FROM T_JFOSS2_ROLE_TO_GROUP WHERE ROLE_ID="
				+ id;
		List groupList = s.createSQLQuery(sql2).list();
		if (groupList != null && groupList.size() > 0) {
			return "2";
		}
		String sql3 = "SELECT RESOURCE_ID FROM T_JFOSS2_RESOURCE_TO_ROLE WHERE ROLE_ID="
				+ id;
		List resourceList = s.createSQLQuery(sql3).list();
		if (resourceList != null && resourceList.size() > 0) {
			return "3";
		} else {
			String sql4 = "DELETE FROM T_JFOSS2_ROLE WHERE ROLE_ID=" + id;
			s.createSQLQuery(sql4).executeUpdate();
			return "0";
		}

	}

	public String deleteRoleByIds(String ids) throws JFossException {
		String returnMessage = null;
		Session s = getSession();

		if (null != ids && !"".equals(ids)) {
			String[] str = ids.split(",");
			if (str.length > 0) {
				for (String id : str) {

					String sql1 = "SELECT USER_ID FROM T_JFOSS2_USER_TO_ROLE WHERE ROLE_ID="
							+ id;
					List userList = s.createSQLQuery(sql1).list();
					if (userList != null && userList.size() > 0) {
						returnMessage = "ID为" + id + "存在与该角色关联的用户，请解除与此关联后再删除";
						throw new JFossException(returnMessage);
					} else {
						String sql2 = "SELECT GROUP_ID FROM T_JFOSS2_ROLE_TO_GROUP WHERE ROLE_ID="
								+ id;
						List groupList = s.createSQLQuery(sql2).list();
						if (groupList != null && groupList.size() > 0) {
							returnMessage = "ID为" + id
									+ "存在与该角色关联的组，请解除与此关联后再删除";
							throw new JFossException(returnMessage);
						} else {
							String sql3 = "SELECT RESOURCE_ID FROM T_JFOSS2_RESOURCE_TO_ROLE WHERE ROLE_ID="
									+ id;
							List resourceList = s.createSQLQuery(sql3).list();
							if (resourceList != null && resourceList.size() > 0) {
								returnMessage = "ID为" + id
										+ "存在与该角色关联的资源，请解除与此关联后再删除";
								throw new JFossException(returnMessage);

							} else {
								String sql4 = "DELETE FROM T_JFOSS2_ROLE WHERE ROLE_ID="
										+ id;
								s.createSQLQuery(sql4).executeUpdate();
							}

						}
					}
				}
			}
		}

		return returnMessage;
	}
	
	public Pager findAllRole(int pageNo, int pageSize) {
		String hql = "from Role r ";
		return this.pagedQuery(hql, pageNo, pageSize);

	}

	protected boolean onValid(Role role) {
		if (role == null) {
			return false;
		} else {
			if (null == role.getId()) { // 新增
				Role role1 = this.findUniqueBy("roleName", role.getRoleName());
				getHibernateTemplate().evict(role1);
				if (null == role1) { // 没有查找到同名的对象
					return true;
				} else { // 已有同名的对象
					return false;
				}
			} else { // 修改
				Role role1 = this.findUniqueBy("roleName", role.getRoleName());
				getHibernateTemplate().evict(role1);
				if (role1 != null) {
					if (role1.getId().equals(role.getId())) { // 同名对象为同一对象，可以保存
						return true;
					} else {
						return false;
					}
				} else {
					return true;
				}
			}
		}
	}

}
